package com.wangshouyu.plugins.swagger;

import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.google.common.base.Optional;
import org.springframework.util.ReflectionUtils;
import springfox.documentation.builders.ModelPropertyBuilder;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;

import java.lang.reflect.Field;

/**
 * @author 王守钰
 * @date 2021-12-27 09:36
 * @description swagger版本模型插件修饰字段
 */
public class VersionPropertyBuilderPlugin implements ModelPropertyBuilderPlugin {

    /**
     * description列
     */
    private static final String DESCRIPTION_FIELD = "description";

    @Override
    public void apply(ModelPropertyContext context) {
        Optional<BeanPropertyDefinition> optional = context.getBeanPropertyDefinition();
        if (optional.isPresent()) {
            try{
                AnnotatedField annotatedField = optional.get().getField();
                Field field = annotatedField.getAnnotated();
                addDescForVersion(context, field);
            }catch (Exception e){}
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }

    private void addDescForVersion(ModelPropertyContext context, Field field) {
        ApiVersion annotation = field.getAnnotation(ApiVersion.class);
        if (annotation != null) {
            String version = annotation.value();
            ModelPropertyBuilder builder = context.getBuilder();
            Field descField = ReflectionUtils.findField(builder.getClass(), DESCRIPTION_FIELD);
            ReflectionUtils.makeAccessible(descField);
            String joinText = ReflectionUtils.getField(descField, builder)
                    + "(" + version + "版本新增)" + annotation.description();
            builder.description(joinText);
        }
    }
}
